import { IVec2Like } from "cc";

export function checkInPolygon(checkPoint: IVec2Like, polygonPoints: IVec2Like[]): boolean {
    const count = polygonPoints.length;
    if (count <= 2) return false;
    let counter = 0, xinters = 0, cp = checkPoint;
    let p1 = polygonPoints[0], p2: IVec2Like = null;
    for (let i = 1; i <= count; i++) {
        p2 = polygonPoints[i % count];
        if (cp.x > Math.min(p1.x, p2.x) && cp.x <= Math.max(p1.x, p2.x)) {
            if (cp.y <= Math.max(p1.y, p2.y)) {
                if (p1.x != p2.x) {
                    xinters = (cp.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
                    if (p1.y == p2.y || cp.y <= xinters) counter++;
                }
            }
        }
        p1 = p2;
    }
    return counter % 2 != 0;
}